<template>
  <div class="basic-layout">
   
    <pro-layout
      v-model:collapsed="baseState.collapsed"
      v-model:selectedKeys="baseState.selectedKeys"
      v-model:openKeys="baseState.openKeys"
      v-bind="state"
      :loading="loading"
      iconfont-url="//at.alicdn.com/t/font_2804900_nzigh7z84gc.js"
    >
      <template #menuHeaderRender>
        <a>
          <h1>晨美国际医美</h1>
        </a>
      </template>
      <!-- custom collapsed button -->
      <template #collapsedButtonRender="collapsed">
        <HeartOutlined v-if="collapsed" />
        <SmileOutlined v-else />
      </template>
      <!-- custom right-content -->
      <template #rightContentRender>
        <resetPassword v-if="state.pwdModalVisible" @cancel="pwdModalCancel"></resetPassword>
        <div style="margin-right: 12px;display:flex;align-items: center;gap:20px">
          <div><span class="primary-color">{{commonStore.$state.user.nickName}}</span><span class="gray-color">,欢迎您登陆</span></div>
          <a-dropdown>
            <a-avatar shape="square" size="small">
            <template #icon>
              <UserOutlined />
            </template>
          </a-avatar>
          <template #overlay>
            <a-menu>
              <a-menu-item>
                <div @click="pwdModalOpen">密码修改</div>
              </a-menu-item>
              <a-menu-item>
                <div @click="logOut" href="javascript:;">退出</div>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
          
        </div>
      </template>
      <!-- content begin -->
      <router-view v-slot="{ Component, route }">
        <a-spin class="page-loading-spinner" :spinning="globalLoadingRef">
          <div>
            <!-- 1. 在Route里设置meta.keepAlive属性，决定是否需要keep-alive -->
            <!-- 2. 设置key是为了解决TypeError: parentComponent.ctx.deactivate is not a function 问题，
                        参考：https://www.gitmemory.com/issue/vuejs/vue-next/1513/653929143
                        解决方案: Make sure to never use NaN as a key. -->
            <keep-alive>
              <component v-if="route.meta.keepAlive" :key="route.name" :is="Component" />
            </keep-alive>
            <component v-if="!route.meta.keepAlive" :is="Component" />
          </div>
        </a-spin>
      </router-view>
    </pro-layout>
  </div>
  
</template>

<script lang="ts">
import { CommonStore } from '@/store';
import { computed, defineComponent, reactive, ref, watchEffect, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { message, Button, Input, Switch, Select, Avatar, Space, Badge, Menu } from 'ant-design-vue';
import { getMenuData, clearMenuItem, WaterMark, FooterToolbar } from '@ant-design-vue/pro-layout';
import type { RouteContextProps } from '@ant-design-vue/pro-layout';
import resetPassword from "@/components/resetPassword/index.vue"
import { RoleService, loginService } from '@/service';

const i18n = (t: string) => t;

const managerAuth=["user","store","goods","packageGroup","goodsCategory","carousel","orders","orderRcord","wxUser","activityPage"]
const cashierAuth=["cashier","orders","orderRcord"]

export default defineComponent({
  name: 'BasicLayout',
  components: {
    FooterToolbar,
    WaterMark,
    [Button.name]: Button,
    [Input.name]: Input,
    [Input.Search.name]: Input.Search,
    [Switch.name]: Switch,
    [Select.name]: Select,
    [Select.Option.displayName!]: Select.Option,
    [Space.name]: Space,
    [Badge.name]: Badge,
    [Avatar.name]: Avatar,
    [Menu.Item.name]: Menu.Item,
    resetPassword
  },
  setup() {
    const loading = ref(false);
    const router = useRouter();
    const commonStore = CommonStore();
    const keepAlivePages = ref('');
    const globalLoadingRef = ref(false);
    const globalLoadingTimerRef = ref<any>(null);

    let { menuData } = getMenuData(clearMenuItem(router.getRoutes()))
 
    const baseState = reactive<Omit<RouteContextProps, 'menuData'>>({
      selectedKeys: [],
      openKeys: [],
      // default
      collapsed: false,
    });

    const state = reactive({
      menuData,
      splitMenus: true,
      title: '限购管理',
      logo: null,
      navTheme: 'dark',
      layout: 'side',
      fixSiderbar: true,
      fixedHeader: true,
      pwdModalVisible:false
    });
    const breadcrumb = computed(() =>
      router.currentRoute.value.matched.concat().map((item) => {
        return {
          path: item.path,
          breadcrumbName: item.meta.title || '',
        };
      }),
    );

    const handleCollapsed = () => {
      baseState.collapsed = !baseState.collapsed;
    };
    watchEffect(() => {
      if (router.currentRoute) {
        const matched = router.currentRoute.value.matched.concat();
        baseState.selectedKeys = matched.filter((r) => r.name !== 'index').map((r) => r.path);
        baseState.openKeys = matched.filter((r) => r.path !== router.currentRoute.value.path).map((r) => r.path);
      }
    });

    watch(commonStore.$state.loadingIdList, (newValue) => {
      /**
       * 全局加载状态处理
       */
      if (!globalLoadingTimerRef.value)
        globalLoadingTimerRef.value = setTimeout(() => {
          globalLoadingRef.value = !!newValue.length;
        }, 200);
      if (!newValue.length) {
        if (globalLoadingTimerRef.value) {
          clearTimeout(globalLoadingTimerRef.value);
          globalLoadingTimerRef.value = null;
        }
        globalLoadingRef.value = !!newValue.length;
      }
    });

    async function getUserRole(){
      let res = await RoleService.findRoleById(commonStore.user.roleId!);
      if(res.code===0){
        commonStore.$state.user.roleValue = res.data.value;
          state.menuData = state.menuData?.filter((menu:any)=>{
            if(res.data.value =="admin")return true;
            if(res.data.value =="manage")return managerAuth.includes(menu.name);
            if(res.data.value =="cashier")return cashierAuth.includes(menu.name);
            return false;
          });
          state.menuData.forEach((item: any) => {
            if (item.meta.keepAlive) {
              keepAlivePages.value += item.name + ',';
            }
          });
        }else{
          state.menuData=[];
          router.push("/404")
        }
    }

    function handlePageLoadingClick() {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 2000);
    }

    function pwdModalOpen(){
      state.pwdModalVisible = true;
    }

    function pwdModalCancel(){
      state.pwdModalVisible = false;
    }

    async function logOut(){
      let res = await loginService.loginOut({userId:commonStore.$state.user.userId!})
      if(res.code===0){
        message.success("操作成功")
        router.replace("/")
      }
    }

    onMounted(() => {
      getUserRole();
    });

    return {
      pwdModalOpen,
      pwdModalCancel,
      logOut,
      i18n,
      commonStore,
      baseState,
      state,
      loading,
      breadcrumb,
      handlePageLoadingClick,
      handleCollapsed,
      keepAlivePages,
      globalLoadingRef,
      handleSearch: () => {
        message.info('search..');
      },
    };
  },
});
</script>
<style lang="less" scoped>
.basic-layout {
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
  :deep(.ant-layout-heade) {
  }
  :deep(.ant-layout) {
    min-height: 100vh;
  }
  :deep(.ant-pro-basicLayout-content) {
    margin: 0;
  }
  :deep(.ant-layout-content) {
    overflow: hidden;
  }
}
</style>
